package com.yuandengta.yomall.product.service.impl;

import com.yuandengta.common.to.SpuBoundTO;
import com.yuandengta.common.utils.R;
import com.yuandengta.yomall.product.entity.SpuInfoDescEntity;
import com.yuandengta.yomall.product.feign.CouponFeignService;
import com.yuandengta.yomall.product.service.*;
import com.yuandengta.yomall.product.vo.BaseAttrs;
import com.yuandengta.yomall.product.vo.Bounds;
import com.yuandengta.yomall.product.vo.Skus;
import com.yuandengta.yomall.product.vo.SpuVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandengta.common.utils.PageUtils;
import com.yuandengta.common.utils.Query;

import com.yuandengta.yomall.product.dao.SpuInfoDao;
import com.yuandengta.yomall.product.entity.SpuInfoEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 发布商品
     * @param spuVO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuVO spuVO) {
        // 1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        // 2.保存spu的描述图片 pms_spu_info_desc
        List<String> decript = spuVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(spuInfoDescEntity);

        // 3.保存spu的图片集 pms_spu_images
        List<String> images = spuVO.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        // 4.保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuVO.getBaseAttrs();
        productAttrValueService.saveProductAttrValue(spuInfoEntity.getId(), baseAttrs);

        // 5.保存spu的积分信息，跨库操作，feign远程调用
        // yomall-sms -> sms_spu_bounds
        Bounds bounds = spuVO.getBounds();
        SpuBoundTO spuBoundTo = new SpuBoundTO();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            // TODO 数据一致性问题：分布式事务解决方案
            log.error("调用远程服务 yomall-coupon 保存积分信息失败");
        }

        // 6.保存spu对应的sku信息
        // sku基本信息 pms_sku_info
        // sku的图片集 pms_sku_images
        // sku的销售属性信息 pms_sku_sale_attr_value
        // sku的满件优惠，满价优惠，会员价等信息，跨库操作
        // yomall-sms -> sms_sku_ladder, sms_sku_full_reduction, sms_member_price
        List<Skus> skus = spuVO.getSkus();
        if (skus != null && skus.size() > 0) {
            skuInfoService.saveSkuInfo(spuInfoEntity, skus);
        }
    }

    /**
     * SPU 检索
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String)params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq("id", key).or().like("spu_name", key);
            });
        }

        String status = (String)params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }

        String brandId = (String)params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }

        String catelogId = (String)params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }
}
